package cn.bigfire.wedesk.service.impl;

import cn.bigfire.wedesk.bean.Wedesk;
import cn.bigfire.wedesk.net.protocol.Protocol;
import cn.bigfire.wedesk.service.bo.Context;
import cn.bigfire.wedesk.service.bo.CustInfo;
import cn.bigfire.wedesk.service.bo.UserEntity;
import cn.bigfire.wedesk.store.Stores;
import cn.bigfire.wedesk.store.Threads;
import cn.hutool.core.convert.Convert;

import java.util.Date;
import java.util.Map;

public class LoginService {

    public static void register(Wedesk.RegisterReq registerReq) {
        //主逻辑
        UserEntity userEntity = Convert.convert(UserEntity.class, registerReq);
        userEntity.setRegisterWay(1);
        userEntity.setRegisterTime(new Date().getTime());
        Stores.register(userEntity);
        //返回值
        Wedesk.RegisterRes registerRes = Convert.convert(Wedesk.RegisterRes.class, userEntity);
        Threads.getContext().send(Protocol.of(Wedesk.Cmd.CMD_REGISTER,registerRes));
    }

    public static void login(Wedesk.LoginReq loginReq) {
        //参数校验
        UserEntity dbUser = Stores.findUserByUsername(loginReq.getUsername());//模拟从数据库取用户
        if (dbUser == null || !loginReq.getPassword().equals(dbUser.getPassword())) {
            Threads.getContext().send(Protocol.err("用户名或密码错误"));
        }
        //构建CustInfo对象
        Context context = Threads.getContext();
        CustInfo custInfo = new CustInfo(context);
        context.setCustInfo(custInfo);
        custInfo.setLoginReq(loginReq);//用户登录时的参数
        custInfo.setUserEntity(dbUser);//用户表数据
        custInfo.setLoginTime(new Date());//用户登录时间
        //主逻辑
        //保存设备信息，并获取当前用户已经在线的设备列表。
        Stores.bindCustPcInfo(Threads.getChannelId(), loginReq.getUsername());

        Map<String, Wedesk.PCInfo> pcInfoMap = Stores.findPcInfosByUsername(loginReq.getUsername());

        //返回值
        Wedesk.LoginRes loginRes = new Wedesk.LoginRes();
        loginRes.setRegisterTime(custInfo.getUserEntity().getRegisterTime());
        loginRes.setUsername(custInfo.getUserEntity().getUsername());
        loginRes.setPcOnlineMap(pcInfoMap);
        custInfo.send(Protocol.of(Wedesk.Cmd.CMD_LOGIN,loginRes));
    }

}
